package com.example.prom.ok.y2023.work.recaptcha;


import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient;
import com.google.recaptchaenterprise.v1.Assessment;
import com.google.recaptchaenterprise.v1.CreateAssessmentRequest;
import com.google.recaptchaenterprise.v1.Event;
import com.google.recaptchaenterprise.v1.ProjectName;
import com.google.recaptchaenterprise.v1.RiskAnalysis.ClassificationReason;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class CreateAssessment {

    public static void main(String[] args) throws IOException {
        // TODO(developer): Replace these variables before running the sample.
        String projectID = "lanzhizhuxia";
        String recaptchaSiteKey = "6Lc4dxolAAAAAGTV9-r3VR5rDtzrbBQUoSEjKzzY";
        String token = "03AFY_a8Ud_sxlp9zAHv0z8IbXEA9SL7nWeAi2wX0-G0sF_t2sHpEuILUMdIRrC1S_6I6lKQD18freYY8KPxixoUpMhOM2XyPs9VxqanU_yhZ8qI-Zr-tsrnPZwygf9aGpKkXI47X_EUZiPdA9-PfLFWFSQxpZmOPHhYzDqNXd0KWxpewKaPKFzyMPueDSPeKMJoaj_bmPmtAI_sxV5CxgxIBrjparbN9Pec1TkoT9S9HVpdjHR1BXbLlZpsVw5TZqQqMXq8lQuAhJQbVbPFqMoMjYPOd50kjekMQIKOVJUrmXWFCsaHhi8bo8xK6TD5HLSFPwnpaKCXxJmj_30KnuXHgiK4mB8TzhWn3Ffij03upll_UYMTxeUtZd3BxPLYISGv7LwK-i4y75CneXePYuwS56Ab1nw8nOyN9mLfKETlCob2R8E5OPBVjVAV_V86DfGFBSpnlZb0qiQsKksqNa5TfmEcKahDNcYa8h1EX0pK9zV1mNJOWm2IMXVV4UBIVZyY0dlwaUU4dPTTQdpq33QAWAByoUHUu-5rfsTTx7t8Lpk61haguzNZHbcHO9ZMNXXCmjSbV6dY247PsJ71_q76KSgh5i1JDcGvYwPMG4i-jcUvtX8L6ZlXZHwEI73ovo33y8n1UIt_lTEMD9Et-10EZL0t0WCdbEcXqBqWPhnvd6IRV_PmmCT2hTfPN99BcRQXNTdKBWHm961L9tE0QETHdq7lAGOpAyUVkYLhIKEnv-4D4ScJ-uShDh0NL6ZhEbSzCurKXwTGRRYet2xdl68_afwtFgicvRGv399nJ7Dmi1c5R6qnFE54KA0HU7dDKasz5kJELs9CLGl8pDYk-BLWh4M-y0k2GdMvaHrLPJ1v0DYP42pMj8tb4wgbl7tfPo8djulO7TiqXeuqAz3QgovKkX3NpuixK8NCD2VNv-xzoQ-CxrK956YVHus3TlXCtQ05qEtqQjxfceMCjpcA4n6-BLq6k7qwqad4fg5UzDCv5A-K2yDGc8DUyE2jsUWetYkf-NQ7Ixxb3mPxNoJKLJbW0dnP9vrtpHkJBxeUPfdeGwxSwUSJADTXTpu_AI-HIKvW004DY-uOvev53iV2Vf_2j0ezHe4assyD1Z27J13qXBsgNca0Y8VNt4RGl9ndaAVPy1ZnYS-fOn0pqHOUuwb3n7lufPMaFuxyCfsv7ph8cC9xNlfKJLVs0YSbq1-DGSt1qWdr8eqi09A_CyUOzeD9UEncBxUo7co1-S0Yrt7Qgy_womn3-P7DIXON6udKxX3Dq5R-jwoXDfMddw9eyxpR-fPpHOYk0wLwQ2LdVji6TpFjy-lw0W-BOxMm8Op5Rfuo0CTMAhQLuaJXTOCt4WHTq71Z2ONQiPqRrxCe-HYxGrYQaJTdDASE9ywBkKIFaLL6OMQMflnem80i41PK0ULomcGjtHbMI_GZnRtHihNuedXGbvZ0HY8QaqhB_4EqznVQaxx0-THzG3ej03rLvBpT3LXkBVWiZVQT1PmQGYuoM08yf99DdjWgKY7bmC78_eUdFKUZh6irPHP3AY0tkCVrj7BiLDHDngGdKTUCdugutzP68MZjUK0csHZbaTdvxG7RnCmqwGFfZUQMZ4tWQOOnYYAuBP64IC6Q";
        String recaptchaAction = "login";

        createAssessment(projectID, recaptchaSiteKey, token, recaptchaAction);
    }

    /**
     * Create an assessment to analyze the risk of an UI action. Assessment approach is the same for
     * both 'score' and 'checkbox' type recaptcha site keys.
     *
     * @param projectID : GCloud Project ID
     * @param recaptchaSiteKey : Site key obtained by registering a domain/app to use recaptcha
     *     services. (score/ checkbox type)
     * @param token : The token obtained from the client on passing the recaptchaSiteKey.
     * @param recaptchaAction : Action name corresponding to the token.
     */
    public static void createAssessment(
            String projectID, String recaptchaSiteKey, String token, String recaptchaAction)
            throws IOException {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests. After completing all of your requests, call
        // the `client.close()` method on the client to safely
        // clean up any remaining background resources.
        try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.create()) {

            // Set the properties of the event to be tracked.
            Event event = Event.newBuilder().setSiteKey(recaptchaSiteKey).setToken(token).build();

            // Build the assessment request.
            CreateAssessmentRequest createAssessmentRequest =
                    CreateAssessmentRequest.newBuilder()
                            .setParent(ProjectName.of(projectID).toString())
                            .setAssessment(Assessment.newBuilder().setEvent(event).build())
                            .build();

            Assessment response = client.createAssessment(createAssessmentRequest);

            // Check if the token is valid.
            if (!response.getTokenProperties().getValid()) {
                System.out.println(
                        "The CreateAssessment call failed because the token was: "
                                + response.getTokenProperties().getInvalidReason().name());
                return;
            }

            // Check if the expected action was executed.
            // (If the key is checkbox type and 'action' attribute wasn't set, skip this check.)
            if (!response.getTokenProperties().getAction().equals(recaptchaAction)) {
                System.out.println(
                        "The action attribute in reCAPTCHA tag is: "
                                + response.getTokenProperties().getAction());
                System.out.println(
                        "The action attribute in the reCAPTCHA tag "
                                + "does not match the action ("
                                + recaptchaAction
                                + ") you are expecting to score");
                return;
            }

            // Get the reason(s) and the risk score.
            // For more information on interpreting the assessment,
            // see: https://cloud.google.com/recaptcha-enterprise/docs/interpret-assessment
            for (ClassificationReason reason : response.getRiskAnalysis().getReasonsList()) {
                System.out.println(reason);
            }

            float recaptchaScore = response.getRiskAnalysis().getScore();
            System.out.println("The reCAPTCHA score is: " + recaptchaScore);

            // Get the assessment name (id). Use this to annotate the assessment.
            String assessmentName = response.getName();
            System.out.println(
                    "Assessment name: " + assessmentName.substring(assessmentName.lastIndexOf("/") + 1));
        }
    }
}